import React, { useState, useRef, useEffect } from "react";
import { Link } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import Slider, { Settings } from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import Choose from "../images/Choose.jpg";
import photoImage from "../images/photo.jpg";
import ruralImage from "../images/rural.jpg";
import Instant from "../images/Instant.jpg";
import free from "../images/free.jpg";
import one from "../images/1.jpg";
import two from "../images/2.jpg";
import three from "../images/3.jpg";
import four from "../images/4.jpg";
import five from "../images/5.jpg";
import six from "../images/6.jpg";
import seven from "../images/7.jpg";
import eight from "../images/8.jpg";
import nine from "../images/9.jpg";
import ten from "../images/10.jpg";
import eleven from "../images/11.jpg";
import twelve from "../images/12.jpg";
import thirteen from "../images/13.jpg";
import fourteen from "../images/14.jpg";
import fifteen from "../images/15.jpg";
import sixteen from "../images/16.jpg";
import seventeen from "../images/17.jpg";
import eighteen from "../images/18.jpg";
import nineteen from "../images/19.jpg";
import twenty from "../images/20.jpg";
import Marquee from 'react-fast-marquee';

const Home: React.FC = () => {
  const [openFaq, setOpenFaq] = useState<number | null>(null);
  const [currentSlide, setCurrentSlide] = useState(0);
  const [hoveredSlide, setHoveredSlide] = useState<number | null>(null);
  const sliderRef = useRef<Slider>(null);
  const [sliderPosition, setSliderPosition] = useState(50);
  const [isDragging, setIsDragging] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const autoMoveRef = useRef<NodeJS.Timeout | null>(null);
  const [mobileCurrentSlide, setMobileCurrentSlide] = useState(0);
  const touchStartX = useRef<number | null>(null);

  // 添加全局样式覆盖Slick默认样式
  useEffect(() => {
    // 创建样式元素
    const styleEl = document.createElement("style");
    styleEl.innerHTML = `
      .slick-slider, .slick-list, .slick-track, .slick-slide > div {
        overflow: visible !important;
      }
      .slick-slide {
        padding: 10px 0;
      }
    `;
    document.head.appendChild(styleEl);

    // 清理函数
    return () => {
      document.head.removeChild(styleEl);
    };
  }, []);

  // 自动缓慢左右移动分割线
  useEffect(() => {
    let direction = 1;
    autoMoveRef.current = setInterval(() => {
      setSliderPosition((prev) => {
        let next = prev + direction * 0.15;
        if (next > 80) {
          next = 80;
          direction = -1;
        } else if (next < 20) {
          next = 20;
          direction = 1;
        }
        return next;
      });
    }, 16); // 约60fps
    return () => {
      if (autoMoveRef.current) clearInterval(autoMoveRef.current);
    };
  }, []);

  const toggleFaq = (index: number) => {
    setOpenFaq(openFaq === index ? null : index);
  };

  const settings: Settings = {
    dots: false,
    infinite: true,
    speed: 500,
    slidesToShow: 3,
    slidesToScroll: 1,
    centerMode: true,
    centerPadding: "50px",
    focusOnSelect: true,
    autoplay: true,
    autoplaySpeed: 2000,
    pauseOnHover: true,
    beforeChange: (current: number, next: number) => setCurrentSlide(next),
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 2,
          centerPadding: "30px",
          autoplay: true,
          autoplaySpeed: 2000,
        },
      },
      {
        breakpoint: 768,
        settings: {
          slidesToShow: 1,
          centerPadding: "20px",
          autoplay: true,
          autoplaySpeed: 2000,
        },
      },
    ],
  };

  const handleMouseDown = () => {
    setIsDragging(true);
    if (autoMoveRef.current) clearInterval(autoMoveRef.current);
  };

  const handleMouseUp = () => {
    setIsDragging(false);
    // 鼠标松开后恢复自动移动
    let direction = sliderPosition > 50 ? 1 : -1;
    autoMoveRef.current = setInterval(() => {
      setSliderPosition((prev) => {
        let next = prev + direction * 0.15;
        if (next > 80) {
          next = 80;
          direction = -1;
        } else if (next < 20) {
          next = 20;
          direction = 1;
        }
        return next;
      });
    }, 16);
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging || !containerRef.current) return;
    const container = containerRef.current;
    const rect = container.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const percentage = (x / rect.width) * 100;
    const boundedPercentage = Math.min(Math.max(percentage, 0), 100);
    setSliderPosition(boundedPercentage);
  };

  useEffect(() => {
    const handleMouseUp = () => setIsDragging(false);
    window.addEventListener("mouseup", handleMouseUp);
    return () => window.removeEventListener("mouseup", handleMouseUp);
  }, []);

  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX;
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (touchStartX.current === null) return;
    const deltaX = e.changedTouches[0].clientX - touchStartX.current;
    if (Math.abs(deltaX) > 40) {
      if (deltaX > 0) setMobileCurrentSlide((prev) => (prev - 1 + 6) % 6);
      else setMobileCurrentSlide((prev) => (prev + 1) % 6);
    }
    touchStartX.current = null;
  };

  // 用户评论数据，头像用真人照片
  const reviews = [
    { name: 'Chris C.', username: 'Renter', body: 'AI helped me solve my layout problems. Saved me so much time!', img: 'https://randomuser.me/api/portraits/men/32.jpg' },
    { name: 'Sophia Z.', username: 'B&B Owner', body: 'Customer support is fast and helpful. The plans are flexible and affordable.', img: 'https://randomuser.me/api/portraits/women/44.jpg' },
    { name: 'Mr. Xu', username: 'Art Teacher', body: 'Even my hand-drawn sketches can be turned into realistic renders. Incredible!', img: 'https://randomuser.me/api/portraits/men/65.jpg' },
    { name: 'Linda S.', username: 'Student', body: 'Mobile experience is smooth, I can design anywhere, anytime on my phone.', img: 'https://randomuser.me/api/portraits/women/68.jpg' },
    { name: 'Olivia F.', username: 'Agency Manager', body: 'Batch processing and team collaboration features are super useful for our agency.', img: 'https://randomuser.me/api/portraits/women/12.jpg' },
    { name: 'David K.', username: 'Tech Enthusiast', body: 'The AI understands my preferences and always surprises me with creative ideas.', img: 'https://randomuser.me/api/portraits/men/23.jpg' },
    { name: 'Anna P.', username: 'Young Professional', body: 'I love how quickly I can try out different furniture and layouts.', img: 'https://randomuser.me/api/portraits/women/29.jpg' },
    { name: 'Kevin L.', username: 'Designer', body: 'The rendering quality is top-notch. My clients are always impressed.', img: 'https://randomuser.me/api/portraits/men/41.jpg' },
    { name: 'Emily R.', username: 'Homeowner', body: 'I never thought I could design my dream room so easily!', img: 'https://randomuser.me/api/portraits/women/50.jpg' },
    { name: 'Tom W.', username: 'Freelancer', body: 'The AI suggestions are spot on. Highly recommended!', img: 'https://randomuser.me/api/portraits/men/77.jpg' },
  ];

  const firstRow = reviews.slice(0, Math.ceil(reviews.length / 2));
  const secondRow = reviews.slice(Math.ceil(reviews.length / 2));

  function ReviewCard({ img, name, username, body }: { img: string; name: string; username: string; body: string }) {
    return (
      <figure
        className={
          'relative h-full w-72 cursor-pointer overflow-hidden rounded-xl border p-6 border-gray-200 bg-white hover:bg-gray-50 transition-all duration-200 shadow-lg scale-105'
        }
      >
        <div className="flex flex-row items-center gap-3">
          <img className="rounded-full border-2 border-blue-200 shadow" width="48" height="48" alt="" src={img} />
          <div className="flex flex-col">
            <figcaption className="text-base font-semibold text-gray-900">{name}</figcaption>
            <p className="text-xs font-medium text-gray-400">{username}</p>
          </div>
        </div>
        <blockquote className="mt-3 text-base text-gray-700 line-clamp-3 h-[4.5em] overflow-hidden">{body}</blockquote>
        <div className="flex mt-2 text-yellow-400">
          {[...Array(5)].map((_, i) => (
            <svg key={i} className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.286 3.967a1 1 0 00.95.69h4.175c.969 0 1.371 1.24.588 1.81l-3.38 2.455a1 1 0 00-.364 1.118l1.287 3.966c.3.922-.755 1.688-1.54 1.118l-3.38-2.454a1 1 0 00-1.175 0l-3.38 2.454c-.784.57-1.838-.196-1.54-1.118l1.287-3.966a1 1 0 00-.364-1.118L2.05 9.394c-.783-.57-.38-1.81.588-1.81h4.175a1 1 0 00.95-.69l1.286-3.967z"/></svg>
          ))}
        </div>
      </figure>
    );
  }

  const roomImages = [
    one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty
  ];

  return (
    <div className="bg-gradient-to-b from-gray-50 to-gray-100">
      <AnimatePresence>
        {/* Hero Section */}
        <motion.div
          key="hero"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="relative bg-blue-50 text-gray-900"
        >
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-24">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 items-center md:justify-items-end">
              <div className="max-w-lg md:justify-self-start">
                <motion.h1
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5 }}
                  className="text-4xl md:text-5xl font-bold mb-6"
                >
                  Transform Your Room with AI
                </motion.h1>
                <motion.p
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                  className="text-xl text-gray-600 mb-8"
                >
                  Upload a photo of your room and let our AI create stunning
                  interior designs in seconds.
                </motion.p>
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: 0.4 }}
                  className="flex md:justify-start justify-center"
                >
                  <Link
                    to="/design"  
                    className="bg-blue-500 text-white px-10 py-4 rounded-lg text-xl font-semibold hover:bg-blue-600 transition-colors inline-block"
                  >
                    Design Room ai now
                  </Link>
                </motion.div>
              </div>
              <div
                className="relative w-full max-w-[900px] h-auto aspect-[3/2] rounded-lg overflow-hidden shadow-xl border-2 border-white"
                ref={containerRef}
                style={{ boxShadow: '0 0 40px 8px #a5b4fc, 0 0 0 4px #fff' }}
              >
                <div className="absolute inset-0" onMouseMove={handleMouseMove}>
                  <img
                    src={ruralImage}
                    alt="Before"
                    className="w-full h-full object-cover"
                  />
                  <div
                    className="absolute inset-0"
                    style={{
                      clipPath: `inset(0 ${100 - sliderPosition}% 0 0)`,
                    }}
                  >
                    <img
                      src={photoImage}
                      alt="After"
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div
                    className="absolute top-0 left-0 h-full flex items-center pointer-events-auto"
                    style={{ left: `${sliderPosition}%` }}
                  >
                    <div className="w-1 h-full bg-gray-300 rounded-full relative flex flex-col items-center justify-center">
                      <div
                        className="absolute top-1/2 -translate-y-1/2 left-1/2 -translate-x-1/2 w-10 h-10 bg-white border-2 border-gray-200 rounded-full flex items-center justify-center shadow-lg transition-all duration-200 cursor-ew-resize hover:scale-110 hover:shadow-[0_0_24px_6px_#60a5fa,0_0_60px_10px_#a5b4fc] group"
                        onMouseDown={handleMouseDown}
                        onTouchStart={handleMouseDown}
                        style={{ boxShadow: '0 0 16px 2px #a5b4fc' }}
                      >
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M8 10l4-4 4 4" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                          <path d="M8 14l4 4 4-4" stroke="#333" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </motion.div>

        {/* Room Showcase Section */}
        <motion.div
          key="showcase"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, delay: 0.2 }}
          className="py-24 bg-white overflow-hidden"
        >
          <div className="w-full">
            <div className="text-center mb-20 px-4 sm:px-6 lg:px-8">
              <h2 className="text-4xl font-bold text-gray-900">
                Rooms that RoomGPT created
              </h2>
              <p className="mt-6 text-2xl text-gray-600">
                See how our AI transforms ordinary rooms into extraordinary
                spaces
              </p>
            </div>
            <RoomGallery images={roomImages} />
          </div>
        </motion.div>

        {/* Features Section */}
        <motion.div
          key="features"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, delay: 0.4 }}
          className="py-24 bg-gray-50"
        >
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-20">
              <h2 className="text-4xl font-bold text-gray-900">
                Why Choose Our AI Room Design Service?
              </h2>
              <p className="mt-6 text-2xl text-gray-600">
                Experience the future of interior design with our AI-powered
                platform
              </p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-12">
              {[
                {
                  title: "Instant Design Suggestions",
                  description:
                    "Get AI-powered design recommendations instantly for your room. Our AI interior design service analyzes your space and provides personalized suggestions.",
                  keywords: [
                    "ai room design",
                    "ai interior design",
                    "room design ai",
                  ],
                  image: Instant,
                },
                {
                  title: "Multiple Style Options",
                  description:
                    "Explore various interior design styles with our AI room generator. From modern to classic, find the perfect look for your space.",
                  keywords: [
                    "ai room generator",
                    "ai design room",
                    "interior design ai",
                  ],
                  image: Choose,
                },
                {
                  title: "Free to Try",
                  description:
                    "Experience our AI interior design free service. No commitment required to see how your room could look with different designs.",
                  keywords: [
                    "ai interior design free",
                    "interior design ai free",
                    "ai for interior design",
                  ],
                  image: free,
                },
              ].map((feature, index) => (
                <motion.div
                  key={index}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: index * 0.2 }}
                  className="bg-white p-8 rounded-xl shadow-sm transition-all duration-300 transform hover:scale-105 hover:shadow-2xl hover:border-2 hover:border-blue-400 hover:z-10 cursor-pointer active:scale-105 active:shadow-2xl active:border-2 active:border-blue-400 focus:scale-105 focus:shadow-2xl focus:border-2 focus:border-blue-400"
                >
                  <div className="aspect-[4/3] mb-8 rounded-lg overflow-hidden">
                    <img
                      src={feature.image}
                      alt={feature.title}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <h3 className="text-2xl font-semibold text-gray-900 mb-6">
                    {feature.title}
                  </h3>
                  <p className="text-xl text-gray-600 mb-6">
                    {feature.description}
                  </p>
                  <div className="flex flex-wrap gap-3">
                    {feature.keywords.map((keyword, i) => (
                      <span
                        key={i}
                        className="px-4 py-2 bg-blue-100 text-blue-600 rounded-full text-base"
                      >
                        {keyword}
                      </span>
                    ))}
                  </div>
                </motion.div>
              ))}
            </div>
          </div>
        </motion.div>

        {/* How It Works Section */}
        <motion.div
          key="how-it-works"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, delay: 0.6 }}
          className="py-20 bg-white"
        >
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-12 items-center">
              {/* Left Column - Phone Mockup */}
              <motion.div
                initial={{ opacity: 0, x: -20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.8 }}
                className="relative"
              >
                <div className="relative w-full max-w-sm mx-auto transition-all duration-300 transform hover:scale-105 hover:shadow-2xl cursor-pointer">
                  <div className="absolute inset-0 bg-gradient-to-r from-blue-200 to-blue-400 rounded-[2.5rem] transform rotate-6"></div>
                  <div className="relative bg-white rounded-[2.5rem] p-2 shadow-2xl">
                    <div className="bg-gray-50 rounded-[2rem] overflow-hidden">
                      <div className="aspect-[9/16] relative flex items-center justify-center">
                        <video
                          src={require('../images/手机.mp4')}
                          autoPlay
                          loop
                          muted
                          playsInline
                          className="w-full h-full object-cover rounded-[2rem]"
                        />
                        <div className="absolute top-4 left-0 w-full text-center pointer-events-none">
                          <h3 className="text-2xl font-bold mb-2 text-gray-900 drop-shadow-lg">Your Dream Room in 15 Second</h3>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </motion.div>

              {/* Right Column - Steps */}
              <motion.div
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ duration: 0.8 }}
                className="space-y-8"
              >
                <h2 className="text-3xl font-bold text-gray-900">
                  How Our AI Room Designer Works
                </h2>
                <p className="text-xl text-gray-600">
                  Transform your space in just a few simple steps
                </p>

                <div className="space-y-6">
                  {[
                    {
                      step: "01",
                      title: "Upload Your Room Photo",
                      description:
                        "Start by uploading a photo of your room. Our AI room planner will use it as the foundation for your custom interior design.",
                    },
                    {
                      step: "02",
                      title: "Choose Design Style",
                      description:
                        "Explore a variety of interior design styles and customize the details to match your vision. Our AI interior designer adapts to your preferences.",
                    },
                    {
                      step: "03",
                      title: "AI Processing",
                      description:
                        "Our AI room generator processes your room and creates stunning designs. The AI considers room dimensions, lighting, and existing elements.",
                    },
                    {
                      step: "04",
                      title: "View Results",
                      description:
                        "See your room transformed with different design options. Get inspired by the AI-generated designs and share with friends and family.",
                    },
                  ].map((step, index) => (
                    <motion.div
                      key={index}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.5, delay: index * 0.2 }}
                      className="flex items-start space-x-4 bg-white rounded-xl p-4 transition-all duration-300 transform hover:scale-105 hover:shadow-2xl hover:border-2 hover:border-purple-400 hover:z-10 cursor-pointer active:scale-105 active:shadow-2xl active:border-2 active:border-purple-400 focus:scale-105 focus:shadow-2xl focus:border-2 focus:border-purple-400"
                    >
                      <div className="flex-shrink-0 w-12 h-12 bg-blue-500 text-white rounded-full flex items-center justify-center text-lg font-bold">
                        {step.step}
                      </div>
                      <div>
                        <h3 className="text-lg font-semibold text-gray-900">
                          {step.title}
                        </h3>
                        <p className="text-gray-600 mt-1">{step.description}</p>
                      </div>
                    </motion.div>
                  ))}
                </div>
              </motion.div>
            </div>
          </div>
        </motion.div>

        {/* Testimonials Section */}
        <section className="py-24 bg-gray-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-20">
              <h2 className="text-5xl font-bold text-gray-900">Loved by many Worldwide</h2>
              <p className="mt-6 text-2xl text-gray-600">See what our over 2 million users are saying about the product</p>
            </div>
            <div className="relative flex w-full flex-col items-center justify-center overflow-hidden gap-6">
              <Marquee pauseOnHover speed={20} gradient gradientWidth={120} className="mb-4">
                {firstRow.map((review) => (
                  <div className="mx-4" key={review.username}>
                    <ReviewCard {...review} />
                  </div>
                ))}
              </Marquee>
              <Marquee pauseOnHover speed={15} gradient gradientWidth={120} direction="right">
                {secondRow.map((review) => (
                  <div className="mx-4" key={review.username}>
                    <ReviewCard {...review} />
                  </div>
                ))}
              </Marquee>
              <div className="pointer-events-none absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-gray-50"></div>
              <div className="pointer-events-none absolute inset-y-0 right-0 w-1/4 bg-gradient-to-l from-gray-50"></div>
            </div>
          </div>
        </section>

        {/* FAQ Section */}
        <motion.div
          key="faq"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, delay: 1.0 }}
          className="py-24 bg-white"
        >
          <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-20">
              <h2 className="text-5xl font-bold text-gray-900">
                Frequently Asked Questions
              </h2>
              <p className="mt-6 text-2xl text-gray-600">
                Find answers to common questions about our AI room design
                service
              </p>
            </div>
            <div className="space-y-6">
              {[
                {
                  number: "01",
                  question: "How does the AI room design service work?",
                  answer:
                    "Our AI interior design service uses advanced algorithms to analyze your room photos and generate personalized design suggestions. Simply upload a photo, choose your preferred style, and let our AI room generator create stunning designs for your space.",
                },
                {
                  number: "02",
                  question: "Is the AI room design service free to use?",
                  answer:
                    "Yes, you can try our AI interior design free service with basic features. We also offer premium plans for more advanced customization options and unlimited designs.",
                },
                {
                  number: "03",
                  question: "What types of rooms can I design?",
                  answer:
                    "Our AI room planner supports various room types including living rooms, bedrooms, kitchens, and home offices. The AI interior designer can adapt to any space and provide relevant design suggestions.",
                },
                {
                  number: "04",
                  question: "How accurate are the AI-generated designs?",
                  answer:
                    "Our AI room design generator uses state-of-the-art technology to create realistic and practical designs. The AI considers room dimensions, lighting, and existing elements to provide accurate and feasible design options.",
                },
                {
                  number: "05",
                  question: "Can I customize the AI-generated designs?",
                  answer:
                    "Yes, our AI design room service allows you to customize various elements like furniture, colors, and layouts. The AI interior designer will adapt to your preferences while maintaining design coherence.",
                },
                {
                  number: "06",
                  question: "How long does it take to generate a design?",
                  answer:
                    "Our AI room generator typically creates designs within minutes. The exact time may vary depending on the complexity of the room and the selected design style.",
                },
              ].map((faq, index) => (
                <motion.div
                  key={index}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: index * 0.1 }}
                  className="bg-gray-50 rounded-xl overflow-hidden"
                >
                  <button
                    onClick={() => toggleFaq(index)}
                    className="w-full px-8 py-6 flex items-center justify-between text-left focus:outline-none"
                  >
                    <div className="flex items-center space-x-6">
                      <span className="text-3xl font-bold text-blue-500">
                        {faq.number}
                      </span>
                      <h3 className="text-2xl font-semibold text-gray-900">
                        {faq.question}
                      </h3>
                    </div>
                    <svg
                      className={`w-8 h-8 text-gray-400 transform transition-transform duration-200 ${
                        openFaq === index ? "rotate-180" : ""
                      }`}
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M19 9l-7 7-7-7"
                      />
                    </svg>
                  </button>
                  {openFaq === index && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: "auto", opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      transition={{ duration: 0.2 }}
                      className="px-8 pb-6"
                    >
                      <p className="text-xl text-gray-600">{faq.answer}</p>
                    </motion.div>
                  )}
                </motion.div>
              ))}
            </div>
          </div>
        </motion.div>
      </AnimatePresence>
    </div>
  );
};

function RoomGallery({ images }: { images: string[] }) {
  const containerRef = React.useRef<HTMLDivElement>(null);
  const offsetRef = React.useRef(0);
  const directionRef = React.useRef(1); // 1: 右, -1: 左
  const [isMobile, setIsMobile] = React.useState(false);
  const speed = 0.4; // px/帧

  React.useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 768);
    };
    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  React.useEffect(() => {
    let running = true;
    const animate = () => {
      if (!containerRef.current) return;
      const container = containerRef.current;
      const containerWidth = container.offsetWidth;
      const contentWidth = container.scrollWidth;
      let nextOffset = offsetRef.current + directionRef.current * speed;
      // 到达边界自动反向
      if (nextOffset > 0) {
        nextOffset = 0;
        directionRef.current = -1;
      } else if (containerWidth - nextOffset > contentWidth) {
        nextOffset = containerWidth - contentWidth;
        directionRef.current = 1;
      }
      offsetRef.current = nextOffset;
      // 直接操作DOM，保证动画丝滑
      container.style.transform = `translateX(${nextOffset}px)`;
      if (running) requestAnimationFrame(animate);
    };
    requestAnimationFrame(animate);
    return () => { running = false; };
  }, []);

  // 移动端手势暂停/恢复动画
  const touchStartX = React.useRef<number | null>(null);
  const [paused, setPaused] = React.useState(false);
  function handleTouchStart(e: React.TouchEvent) {
    setPaused(true);
    touchStartX.current = e.touches[0].clientX;
  }
  function handleTouchEnd(e: React.TouchEvent) {
    setPaused(false);
    touchStartX.current = null;
  }

  // 动画暂停/恢复
  React.useEffect(() => {
    if (!paused) {
      let running = true;
      const animate = () => {
        if (!containerRef.current) return;
        const container = containerRef.current;
        const containerWidth = container.offsetWidth;
        const contentWidth = container.scrollWidth;
        let nextOffset = offsetRef.current + directionRef.current * speed;
        if (nextOffset > 0) {
          nextOffset = 0;
          directionRef.current = -1;
        } else if (containerWidth - nextOffset > contentWidth) {
          nextOffset = containerWidth - contentWidth;
          directionRef.current = 1;
        }
        offsetRef.current = nextOffset;
        container.style.transform = `translateX(${nextOffset}px)`;
        if (running) requestAnimationFrame(animate);
      };
      requestAnimationFrame(animate);
      return () => { running = false; };
    }
  }, [paused]);

  return (
    <div
      className="relative w-full overflow-hidden"
      style={{ height: isMobile ? 180 : 320 }}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      <div
        ref={containerRef}
        className="flex items-center gap-2 will-change-transform"
        style={{ transition: paused ? 'transform 0.3s' : undefined }}
      >
        {images.map((img, idx) => (
          <div
            key={idx}
            className="flex-shrink-0 rounded-xl shadow-lg bg-white"
            style={{ width: isMobile ? 220 : 340, height: isMobile ? 160 : 280 }}
          >
            <img
              src={img}
              alt={`Room design ${idx + 1}`}
              className="w-full h-full object-cover rounded-xl"
              draggable={false}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

export default Home;
